package com.wxy.netty.协议;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.Charset;

/**
 * @author 47868
 */
public class RedisTest {
    static final String LINE = "\r\n";
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Channel channel = new Bootstrap()
                .group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                ByteBuf byteBuf = ctx.alloc().buffer();
                                byteBuf.writeBytes("*3".getBytes());
                                byteBuf.writeBytes(LINE.getBytes());
                                byteBuf.writeBytes("$3".getBytes());
                                byteBuf.writeBytes(LINE.getBytes());
                                byteBuf.writeBytes("set".getBytes());
                                byteBuf.writeBytes(LINE.getBytes());
                                byteBuf.writeBytes("$5".getBytes());
                                byteBuf.writeBytes(LINE.getBytes());
                                byteBuf.writeBytes("user1".getBytes());
                                byteBuf.writeBytes(LINE.getBytes());
                                byteBuf.writeBytes("$4".getBytes());
                                byteBuf.writeBytes(LINE.getBytes());
                                byteBuf.writeBytes("lisi".getBytes());
                                byteBuf.writeBytes(LINE.getBytes());
                                ctx.writeAndFlush(byteBuf);
                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                System.out.println(byteBuf.toString(Charset.defaultCharset()));
                                ctx.close();
                            }
                        });
                    }
                }).connect("localhost",6379).sync().channel();
        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener((ChannelFutureListener) channelFuture -> eventLoopGroup.shutdownGracefully());
    }
}
